package features.advance.jdk.regexp;

import com.singularsys.jep.Jep;
import com.singularsys.jep.parser.Node;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *  java 正则表达式的规则验证
 * @author LIN
 * @date 2021-12-11 13:21
 */
public class PatternDemo {

    public static void main(String[] args) {

        boolean matches = Pattern.matches("this\\s+is\\s+text", "this   is    text");
        /*
         *Matcher.matches();
         *entire region
         */
        System.out.println(matches);
        // \s匹配空格
        println("this   is    text","this\\s+is\\s+text");

        println("1 ","^\\s");

        println("sum(a1:a3,a4,sum(1,2,3,4,5)+sum)","sum\\((?!.*(sum\\(.*\\))).*\\)");

        // 应该用*匹配0到多个(，还是应该用+匹配1到多个(
        println("sum(sum((((((a1,2,3))+sum","sum\\((?!sum\\(*)");

        // 分组匹配规则

        println("","(\\D*)(.*)");
        // \1对第一个匹配的引用，\num对第num个匹配的引用
        // TODO 有待探究，这些匹配是在缓冲区里？
        /*
         * (pattern)
         *
         * 匹配 pattern 并捕获该匹配的子表达式。
         * 可以使用 $0…$9 属性从结果"匹配"集合中检索捕获的匹配。
         * 若要匹配括号字符 ( )，请使用"\("或者"\)"。
         */
        println("aa131202bbbbsumbb202","(.)(sum)\\1\\1");
        System.out.println(Pattern.matches("(.)(sum)\\1\\1","bsumbb"));
        /*
        (?:)匹配的内容，不放到缓冲区里
         */

        /*
        分组匹配
         */
        Pattern compile = Pattern.compile("(.)(.)");
        Matcher matcher = compile.matcher("123");
        if(matcher.find()){
            for (int i = 0; i < matcher.groupCount(); i++) {
                String group = matcher.group(i);
                System.out.println("group"+i+":"+group);
            }
        }
        Jep jep = new Jep();

        try{
            Object evaluate = jep.evaluate(jep.parse("1+1"));
            System.out.println(evaluate);
            Node parse1 = jep.parse("a1=a2+5");
            Node parse = jep.parse("b1=sum(a1+a2,sum(1,2,3,4,5),pow(9,3))");
            jep.addVariable("a2",2);
            jep.evaluate(parse1);
            jep.evaluate(parse);
            System.out.println(jep.getVariable("b1").getValue());
        }catch (Exception e){
            e.printStackTrace();
        }


        

    }

    public static void println(String str,String reg){
        Matcher matcher = Pattern.compile(reg).matcher(str);
        if(matcher.find()){
            System.out.println(str.substring(matcher.start(), matcher.end()));
            while (matcher.find()){
                System.out.println(str.substring(matcher.start(), matcher.end()));
            }
        }else{
            System.out.println("Regexp:"+reg+"\t"+str+"未匹配到");
        }
    }

    public static void println(String str,String reg,int groupCount){

    }


}
